package com.adb.androidwebalbum.ui;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;

import com.adb.androidwebalbum.R;
import com.adb.androidwebalbum.bean.ImageBean;
import com.adb.androidwebalbum.uc.ApplicationTopBar;
import com.adb.androidwebalbum.uc.ImageGalleryAdapter;
import com.adb.androidwebalbum.uc.OnHeadNavigationSelectedListener;
import com.adb.androidwebalbum.utils.Const;
import com.adb.androidwebalbum.utils.JSONParser;
import com.adb.androidwebalbum.utils.Log;
import com.adb.androidwebalbum.utils.Utility;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

public class ThumbnailPhotoActivity extends BaseActivity implements OnItemClickListener,OnHeadNavigationSelectedListener{
	
public final String TAG = ThumbnailPhotoActivity.class.getCanonicalName();

	private ImageView view_navigation;
	private ApplicationTopBar mApplicationTopBar;
	private GridView view_grid;
	private ImageGalleryAdapter mImageAdapter;
	private DisplayImageOptions options;
	public  ArrayList<ImageBean> mBeanofImages = new ArrayList<ImageBean>();
	private ProgressDialog mProgressDialog;
	
	
	 // JSON Node names
    private static final String TAG_PHOTOS = "Photos";
    private static final String TAG_CAPTION = "Caption";
    private static final String TAG_PHOTO_ID = "PhotoID";
    private static final String TAG_DISP_ORDER = "DisplayOrder";
    private static final String TAG_LARGE_FILE_PATH = "FilePath";
    private static final String TAG_THUMB_FILE_PATH = "ThumbPath";
    private static final int ACTIVITY_REQUEST_CODE = 100;
    
    private int stratPoint = 0;
    
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	
    	if(requestCode == ACTIVITY_REQUEST_CODE){
//    		if(data != null){
//    			stratPoint = 0;
//    			if(mBeanofImages != null){
//    				mBeanofImages.clear();
//    			}
//    			mImageAdapter.removeAllIteams();
//    			
//    			new RetrievePhotoList().execute(new String[]{String.valueOf(stratPoint)});
//    		}
    		
    	}
    		
    }
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Const.CONTEXT = ThumbnailPhotoActivity.this;
		setContentView(R.layout.activity_thumnail_photos);
		Log.debug(TAG,"[ onCreate ] ");
		
		options = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.icon_menu_refresh)
		.showStubImage(R.drawable.icon_menu_refresh)
		.cacheInMemory()
		.cacheOnDisc()
		.build();
		
		mApplicationTopBar = (ApplicationTopBar)findViewById(R.id.applicationTopBar);
		mApplicationTopBar.setAppTopBarText(getResources().getString(R.string.top_name));
		
		
		mImageAdapter = new ImageGalleryAdapter(this,imageLoader,options);
		
		
		view_grid = (GridView) this.findViewById(R.id.view_grid);	
		view_grid.setOnItemClickListener(this);
		view_grid.setAdapter(mImageAdapter);
		
		
		mProgressDialog = new ProgressDialog(ThumbnailPhotoActivity.this);
		mProgressDialog.setMessage("Please wait....");
		mProgressDialog.setIndeterminate(true);
		mProgressDialog.setCancelable(false);
		
		view_navigation = (ImageView)findViewById(R.id.view_navigation);
		view_navigation.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				

				 new AlertDialog.Builder(ThumbnailPhotoActivity.this)
				 .setMessage("Do you want to exit ?")
				 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

				        // do something when the button is clicked
				        public void onClick(DialogInterface arg0, int arg1) {

				            finish();
				            //close();
				        }
				    })
				    .setNegativeButton("No", new DialogInterface.OnClickListener() {

				        // do something when the button is clicked
				        public void onClick(DialogInterface arg0, int arg1) {
		               }
				    })
			      .show();
				 
			
			}
		});
		
		
		new RetrievePhotoList().execute(new String[]{String.valueOf(stratPoint)});
		
	}
	@Override
	protected void onStart() {
		super.onStart();
		Log.debug(TAG,"[ onStart ] ");
	}
	@Override
	protected void onStop() {
		super.onStop();
		Log.debug(TAG,"[ onStop ] ");
	}
	@Override
	protected void onPause() {
		super.onPause();
		Log.debug(TAG,"[ onPause ] ");
	
    	
	}
	@Override
	protected void onResume() {
		super.onResume();
		Log.debug(TAG,"[ onResume ] ");
	
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.debug(TAG,"[ onDestroy ] ");
	}
	
	
	@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.options_menu,menu);
			return true;

		}
	
	@Override
		public boolean onOptionsItemSelected(MenuItem item) {
		
			switch (item.getItemId()) {
			case R.id.menu_loadmore:
				stratPoint = stratPoint + 20;
				new RetrievePhotoList().execute(new String[]{String.valueOf(stratPoint)});
				break;
			default:
				break;
			}
			return super.onOptionsItemSelected(item);
		}
	
	private class RetrievePhotoList extends AsyncTask<String,Void, Integer>{
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
			mApplicationTopBar.makeIndeterminateProgressStart();
		}
		
		@Override
		protected Integer doInBackground(String... params) {
			int errorNo = 0;
			
			// contacts JSONArray
		    JSONArray mPhotosJsonArray = null;
		     // Creating JSON Parser instance
	        JSONParser jParser = new JSONParser();
	        // getting JSON string from URL
	        JSONObject mJson = jParser.getJSONFromUrl(Const.OPERATION_GET_PHOTOS,params[0],"20");
	        
	        try {
	            // Getting Array of Photos
	            mPhotosJsonArray = mJson.getJSONArray(TAG_PHOTOS);
	            // create object of ImageBean
	            ImageBean mBeanofPhoto;
	            // looping through All Photos
	            for(int i = 0; i < mPhotosJsonArray.length(); i++){
	            	
	            	mBeanofPhoto = new ImageBean();
	            	JSONObject mObjectPhoto = mPhotosJsonArray.getJSONObject(i);
	 
	            	// Storing each json item in variable
	                String caption = mObjectPhoto.getString(TAG_CAPTION);
	                String displayOrder = mObjectPhoto.getString(TAG_DISP_ORDER);
	                String filePath = mObjectPhoto.getString(TAG_LARGE_FILE_PATH);
	                String photoID = mObjectPhoto.getString(TAG_PHOTO_ID);
	                String thumPath = mObjectPhoto.getString(TAG_THUMB_FILE_PATH);
	                
	                
	                mBeanofPhoto.setmTag(photoID);
	                mBeanofPhoto.setCaption(caption);
	                mBeanofPhoto.setDispayorder(displayOrder);
	                mBeanofPhoto.setLarge_filepath(filePath);
	                mBeanofPhoto.setPhotoId(photoID);
	                mBeanofPhoto.setThumbpath(thumPath);
	                
	                
	                //finally added inside array list 
	                mBeanofImages.add(mBeanofPhoto);
	                Utility.writeObject(Const.FILE_PHOTOS_LIST,mBeanofImages);
	            }
	        } catch (JSONException e) {
	            e.printStackTrace();
	        }
	        
			return errorNo;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			mApplicationTopBar.makeIndeterminateProgressStop();
			if(result == 0){
				
				Log.debug(TAG,"SIZE " + mBeanofImages.size());
				mImageAdapter.addItemArrayList(mBeanofImages);
			}
		}
		
	}

	public void onItemClick(AdapterView<?> parent, View mView, int position, long id) {
//		
//		Intent mIntent = new Intent(ThumbnailPhotoActivity.this,PhotosViewerActivity.class);
//		mIntent.putExtra(Const.INTENT_POSITION,position+"");
//		startActivity(mIntent);
		
		final Intent i = new Intent(ThumbnailPhotoActivity.this, ImageDetailActivity.class);
        i.putExtra(ImageDetailActivity.EXTRA_IMAGE,position);
        startActivityForResult(i,ACTIVITY_REQUEST_CODE);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
			
		  new AlertDialog.Builder(ThumbnailPhotoActivity.this)
		 .setMessage("Do you want to exit ?")
		 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

		        // do something when the button is clicked
		        public void onClick(DialogInterface arg0, int arg1) {

		            finish();
		            //close();


		        }
		    })
		    .setNegativeButton("No", new DialogInterface.OnClickListener() {

		        // do something when the button is clicked
		        public void onClick(DialogInterface arg0, int arg1) {
               }
		    })
	      .show();
		 return true;
	}

	public void onButtonSelected(int id) {
		switch (id) {
		case R.id.menu_refresh:
			stratPoint = stratPoint + 20;
			new RetrievePhotoList().execute(new String[]{String.valueOf(stratPoint)});
			break;

		default:
			break;
		}
	}

	class ScrollPositioner {
	    private static final int SCROLL_DURATION = 20;
	    private static final int DIR_UP = 1;
	    private static final int DIR_DOWN = 2;

	    int mTargetPosition = AdapterView.INVALID_POSITION;
	    int mDirection = AdapterView.INVALID_POSITION;
	    int mLastSeenPosition = AdapterView.INVALID_POSITION;
	    int mExtraScroll;
	    GridView mGrid;

	    public ScrollPositioner(GridView grid) {
	        mGrid = grid;
	        mExtraScroll = ViewConfiguration.get(mGrid.getContext()).getScaledFadingEdgeLength();
	    }
	    public void removerGridView(){
	    	mGrid = null;
	    }
	    Handler mHandler = new Handler();
	    Runnable mScroller = new Runnable() {
	        public void run() {
	            int firstPos = mGrid.getFirstVisiblePosition();
	            switch(mDirection) {
	            case DIR_UP: {
	                if (firstPos == mLastSeenPosition) {
	                    // No new views, let things keep going.
	                    mHandler.postDelayed(mScroller, SCROLL_DURATION);
	                    return;
	                }

	                final View firstView = mGrid.getChildAt(0);
	                if (firstView == null) {
	                    return;
	                }
	                final int firstViewTop = firstView.getTop();
	                final int extraScroll = firstPos > 0 ? mExtraScroll : mGrid.getPaddingTop();

	                mGrid.smoothScrollBy(firstViewTop - extraScroll, SCROLL_DURATION);

	                mLastSeenPosition = firstPos;

	                if (firstPos > mTargetPosition) {
	                    mHandler.postDelayed(mScroller, SCROLL_DURATION);
	                }
	                break;
	            }

	            case DIR_DOWN: {
	                final int lastViewIndex = mGrid.getChildCount() - 1;
	                final int lastPos = firstPos + lastViewIndex;

	                if (lastViewIndex < 0) {
	                    return;
	                }

	                if (lastPos == mLastSeenPosition) {
	                    // No new views, let things keep going.
	                    mHandler.postDelayed(mScroller, SCROLL_DURATION);
	                    return;
	                }

	                final View lastView = mGrid.getChildAt(lastViewIndex);
	                final int lastViewHeight = lastView.getHeight();
	                final int lastViewTop = lastView.getTop();
	                final int lastViewPixelsShowing = mGrid.getHeight() - lastViewTop;
	                final int extraScroll = lastPos < mGrid.getAdapter().getCount() - 1 ? mExtraScroll : mGrid.getPaddingBottom();

	                mGrid.smoothScrollBy(lastViewHeight - lastViewPixelsShowing + extraScroll, SCROLL_DURATION);

	                mLastSeenPosition = lastPos;
	                if (lastPos < mTargetPosition) {
	                    mHandler.postDelayed(mScroller, SCROLL_DURATION);
	                }
	                break;
	            }

	            default:
	                break;
	            }
	        }
	    };

	    public void scrollToPosition(int position) {
	        mTargetPosition = position;
	        mLastSeenPosition = AdapterView.INVALID_POSITION;

	        if(position < mGrid.getFirstVisiblePosition()) {
	            mDirection = DIR_UP;
	        } else if (position > mGrid.getLastVisiblePosition()) {
	            mDirection = DIR_DOWN;
	        } else {
	            return;
	        }
	        mHandler.post(mScroller);
	    }
	}
}
